//
//  OPPersonalInbox.m
//  OPFramework
//
//  Created by malcom on 7/23/08.
//  Copyright 2008 malcom-mac software. All rights reserved.
//

#import "OPPersonalInbox.h"
#import "OPBoard.h"
#import "OPPrivateMsg.h"

@implementation OPPersonalInbox

@synthesize p_unread_privateMsgs;

- (id) _initWithAuthorizedUser:(OPAuthUser *) _user {
	self = [super init];
	if (self != nil) {
		_delegateBoard = [_user._delegateBoard retain];
		p_unread_privateMsgs = -1;
		p_privateMsgsList = nil;
	}
	return self;
}

- (BOOL) refreshData {	
	XMLRPCResponse *_unreadMsgs = [_delegateBoard _executeRequestMethodNamed: @"user.countUnreadPrivateMessages" 
																		   withParams: nil
																	   attachAuthData: NO];
	if ([_unreadMsgs isFault]) return NO;
	else p_unread_privateMsgs = [[_unreadMsgs responseObject] intValue];
	
	return YES;
}

#define _method_getUnreadMsgs @"user.getUnreadPrivateMessages" 
- (NSArray *) getPrivateMessages {
	if (p_privateMsgsList == nil || [self isCacheExpired])
		[self sendXMLRequestForMethod: _method_getUnreadMsgs withParams: nil parseSelector: @selector(_parseUnreadLists:)];
	return p_privateMsgsList;
}

- (void)connection: (XMLRPCConnection *)connection didReceiveResponse:(XMLRPCResponse *)response forMethod: (NSString *)method {
	// super class check if it's an error, a numeric response or simply some data to parse
	if (![self _checkErrorInRawResponseFromServer: response forMethod:method]) {
		// data update to parse
		[self _parseUnreadLists: [NSArray arrayWithObjects: [response responseObject],method,nil]];
		// we can propagate the result to listeners
		[self dataUpdatedFor: self atMethod:method];	
	}
}

- (BOOL) _isNumericResponseFromServerAnErrorCode:(NSNumber *) _code forMethod:(NSString *) method {
	return NO;
}

- (void) _parseUnreadLists:(NSArray *) _result {
	NSArray *_list = [_result objectAtIndex: 0];
	[p_privateMsgsList release]; p_privateMsgsList = [[NSMutableArray alloc] init];
	
	for (NSDictionary *cMsg in _list) {
		OPPrivateMsg *msg = [[OPPrivateMsg alloc] _initLoadingDataResponse: cMsg forBoard: _delegateBoard];
		[p_privateMsgsList addObject: msg];
	}
}

- (BOOL) sendNewPrivateMessageTo:(OPUser *) _user withSubject:(NSString *) _subj text:(NSString *) _text options:(NSDictionary *) _options {
	return [OPPrivateMsg _sendMessageWithMode: @"post" toUser:[NSNumber numberWithInt: _user.p_userid] withSubject:_subj text:_text replyTo: nil options:_options board: _delegateBoard];
}

@end
